<?php

namespace app\admin\controller;

use app\admin\controller\Base;
use \think\Request;
use think\facade\View;
use app\common\model\Coupon as CouponModel;
use app\common\model\GoodsList;
use app\common\model\User;
use app\common\model\AdminGoodsLog;
use app\common\model\ConvertCode as ConvertCodeModel;
use app\common\model\ConvertCodeReceive;

class ConvertCode extends Base
{
    /**
     * 兑换码列表
     */
    public function index(Request $request)
    {
        $keyword = trim(input('get.keyword'));
        $status = trim(input('get.status'));
        $whe = [];
        if (!empty($keyword)) {
            $whe[] = ['code', 'like', '%' . $keyword . '%'];
        }
        if (!empty($status)) {
            if ($status == 2) {
                $status = 0;
            }
            $whe[] = ['status', '=', $status];
        } else {
            $whe[] = ['status', '<', 3];
        }
        $field = "*";
        $order = "addtime desc";
        $data = ConvertCodeModel::getList($whe, $field, $order, $this->page);
        foreach ($data['list'] as $k => &$v) {
            $v['coupon_title'] = CouponModel::where(['id'=> $v['coupon_id']])->value('title');
            $v['goodslist_title'] = GoodsList::where(['id'=> $v['goodslist_id']])->value('title');
        }
        
        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        return View::fetch("ConvertCode/index");

    }

    /**
     * 领取记录
     */ 
    public function convert_code_receive(Request $request)
    {
        $keyword = trim(input('get.keyword'));
        $user_id = trim(input('get.user_id'));

        $whe = [];
        if (!empty($keyword)) {
            $whe[] = ['code', 'like', '%' . $keyword . '%'];
        }
        if (!empty($status)) {
            $whe[] = ['user_id', '=', $user_id];
        } 
        
        $field = "*";
        $order = "addtime desc";
        $data = ConvertCodeReceive::getList($whe, $field, $order, $this->page);
        foreach ($data['list'] as $k => &$v) {
            $uset_info = User::where(['id'=> $v['user_id']])->field('nickname, headimg, id')->find();
            $v['nickname'] = $uset_info['nickname'];
            $v['headimg'] = $uset_info['headimg'];
            $v['coupon_title'] = CouponModel::where(['id'=> $v['coupon_id']])->value('title');
            $v['goodslist_title'] = GoodsList::where(['id'=> $v['goodslist_id']])->value('title');
        }
        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        return View::fetch("ConvertCode/convert_code_receive");
    }
    /**
     * 添加商品
     */
    public function add(Request $request)
    {
        if (!$request->isPost()) {
            //优惠券
            $where = [];
            $where[] = ['type', '=', 3];
            $where[] = ['status', '=', 0];
            $coupon = CouponModel::getAllList($where, '*');
            View::assign('coupon', $coupon);
            //兑换码商品
            $where = [];
            $where[] = ['goods_id', '=', '-5'];
            $goodslist = GoodsList::getAllList($where, '*');
            View::assign('goodslist', $goodslist);
            return View::fetch("ConvertCode/add");
        } else {
            $data = input('post.');
            $check = ConvertCodeModel::getInfo(['code' => $data['code']]);
            if (empty($data['code'])) {
                return $this->renderError("兑换码请填写");
            }
            if (!empty($check)) {
                return $this->renderError("兑换码已存在");
            }
            if (!empty($data['coupon_id']) and !empty($data['goodslist_id'])  ) {
                return $this->renderError("优惠券/商品二选其一");
            }
            if (empty($data['coupon_id']) and empty($data['goodslist_id'])  ) {
                return $this->renderError("优惠券/商品二选其一");
            }
            $data['addtime'] = time();
            $dd = ConvertCodeModel::insertGetId($data);
            if ($dd) {
                return $this->renderSuccess("添加成功");
            } else {
                return $this->renderError("网络繁忙，请稍后");
            }
        }
    }

    /**
     * 编辑商品
     */
    public function edit(Request $request)
    {
        if (!$request->isPost()) {
            $id = $request->param('id');
            //优惠券
            $where = [];
            $where[] = ['type', '=', 3];
            $where[] = ['status', '=', 0];

            $coupon = CouponModel::getAllList($where, '*');
            View::assign('coupons', $coupon);
            //兑换码商品
            $where = [];
            $where[] = ['goods_id', '=', '-5'];
            $goodslist = GoodsList::getAllList($where, '*');
            View::assign('goodslist', $goodslist);
            
            $code = ConvertCodeModel::getInfo(['id' => $id], '*');
            View::assign('code', $code);
            return View::fetch("ConvertCode/edit");
        } else {
            $data = input('post.');
            // dd($data);
            ConvertCodeModel::startTrans();
            $id = $data['id'];
            unset($data['id']);
            // if (empty($data['code'])) {
            //     return $this->renderError("兑换码请填写");
            // }
            if (!empty($data['coupon_id']) and !empty($data['goodslist_id'])  ) {
                return $this->renderError("优惠券/商品二选其一");
            }
            if (empty($data['coupon_id']) and empty($data['goodslist_id'])  ) {
                return $this->renderError("优惠券/商品二选其一");
            }
            $dd = ConvertCodeModel::where(['id' => $id])->update($data);

            if ($dd) {
                ConvertCodeModel::commit();
                return $this->renderSuccess("编辑成功");
            } else {
                ConvertCodeModel::rollback();
                return $this->renderError("网络繁忙，请稍后");
            }
        }
    }
    
    

    //上、下架商品
    public function cao(Request $request)
    {
        $id = $request->post('id/d');
        $status = $request->post('type/d');
        if (!in_array($status, array(1, 2, 4))) {
            return $this->renderError("数据错误");
        }
        $data = ConvertCodeModel::where(['id' => $id])->field('id')->find();
        if (!$data) {
            return $this->renderError("数据不存在");
        }
        $result = ConvertCodeModel::where(['id' => $id])->update(["status" => $status]);
        if ($result) {
            return $this->renderSuccess("操作成功");
        } else {
            return $this->renderError("网络繁忙，请稍后");
        }
    }


    /**
     * 盒子奖品
     */
    public function goodslist(Request $request)
    {

        $title = trim(input('get.title'));
        $whe = array();
        $whe[] = ['status', '=', 1];
        $whe[] = ['goods_id', '=', '-5'];  //  兑换码商品
        if (!empty($title)) {
            $whe[] = ['title', 'like', '%' . $title . '%'];
        }
        $field = "*";
        $order = "sort desc,shang_id asc,id asc";
        $data = GoodsList::getList($whe, $field, $order, $this->page);

        // foreach ($data['list'] as &$value) {
//             $value['shang'] = Shang::where(['id' => $value['shang_id']])->value('title');
// //            if ($value['goods_type'] == 2) {
// //                $value['sale_time'] = date('Y-m-d', $value['sale_time']);
// //            } else {
// //                $value['sale_time'] = '';
// //            }
//             if($nums>0){
//                 $value['num'] = self::jisuan(self::jisuan($value['gailv'],$nums,'/',5),100,'*',3);
//             }else{
//                 $value['num'] = 0;
//             }
//             $real_pro += $value['num'];
        // }
        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        return View::fetch("ConvertCode/goodslist");
    }
    
    /**
     * 添加奖品
     */
    public function goodslist_add(Request $request)
    {
        if (!$request->isPost()) {
            return View::fetch('ConvertCode/goodslist_add');
        } else {
            $data = input('post.');
            if (RegMoney($data['money'])) {  
                return $this->renderError('兑换价格设置错误,最多保留两位小数');
            }
            $save_sports_data = [];
            if (empty($data['imgurl'])) {
                return $this->renderError('请上传图片');
            }
            $data['card_no'] = NULL;
            if (empty($data['imgurl'])) {
                return $this->renderError('请上传图片');
            }
            $data['addtime'] = time();
            $data['goods_id'] = '-5';
            
            $data['prize_code'] = getPrizeCode() . '_' . time();
            $res = GoodsList::insert($data);
            
            if ($res) {
                return $this->renderSuccess('添加成功');
            } else {
                return $this->renderError('添加失败');
            }
        }
    }

    /**
     * 编辑奖品
     */
    public function goodslist_edit(Request $request)
    {
        if (!$request->isPost()) {
            $id = $request->param('id/d', 0);
            $goods = GoodsList::where(['id' => $id])->find();
            if (!$goods) {
                return $this->renderError('请求参数错误');
            }
        
            View::assign('goods', $goods);
            return View::fetch('ConvertCode/goodslist_edit');
        } else {
            $data = input('post.');
            if (empty($data['id'])) {
                return $this->renderError('请求参数错误1');
            }
            $goods = GoodsList::where(['id' => $data['id']])->find();
            if (!$goods) {
                return $this->renderError('请求参数错误2');
            }
            if (empty($data['title'])) {
                return $this->renderError('请输入奖品名称');
            }

            if (RegMoney($data['money'])) {
                return $this->renderError('兑换价格设置错误,最多保留两位小数');
            }
            
            if (RegZero($data['sort'])) {
                return $this->renderError('排序请输入整数');
            }

            $data['card_no'] = NULL;
            if (empty($data['imgurl'])) {
                return $this->renderError('请上传图片');
            }
            $id = $data['id'];
            unset($data['id']);
            $data['update_time'] = time();
          
            $res1 = GoodsList::where(['id' => $id])->update($data);
        
            if ($res1) {
                //添加日志
                $goods['update_time'] = date('Y-m-d H:i:i:s',$goods['update_time']);
                $data['update_time'] = date('Y-m-d H:i:i:s',$data['update_time']);
                $res2 = AdminGoodsLog::add_goods_log(session('admin_id'),'-5',$goods['id'],json_encode($goods),json_encode($data));
                return $this->renderSuccess('编辑成功');
            } else {
                return $this->renderError('编辑失败');
            }
        }
    }
    
    
    /**
     * 上、下架,删除盒子
     */
    public function goodslist_del(Request $request)
    {
        $id = $request->post('id/d');
        $status = $request->post('type/d');
        $data = GoodsList::where(['id' => $id])->field('id')->find();
        if (!$data) {
            return $this->renderError("数据不存在");
        }
        $result = GoodsList::where(['id' => $id])->update(['status' => 2]);
        if ($result) {
            return $this->renderSuccess("操作成功");
        } else {
            return $this->renderError("网络繁忙，请稍后");
        }
    }
     /**
     * 上、下架,删除盒子
     */
    public function convert_del(Request $request)
    {
        $id = $request->post('id/d');
        $status = $request->post('type/d');
        $data = ConvertCodeModel::where(['id' => $id])->field('id')->find();
        if (!$data) {
            return $this->renderError("数据不存在");
        }
        $result = ConvertCodeModel::where(['id' => $id])->update(['status' => 3]);
        if ($result) {
            return $this->renderSuccess("操作成功");
        } else {
            return $this->renderError("网络繁忙，请稍后");
        }
    }

}
